using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using SPVisualDev.Services;
using System.Reflection;
using SPVisualDev.VSAddin.Services;

namespace SPVisualDev.VSAddin.Dialogs
{
    public partial class DialogArtifactConfig : Form
    {
        private SpecialProject m_project;
        private SpecialSolution m_solution;
        private Dictionary<string, string> m_last_config_values = new Dictionary<string, string>();
        private List<DialogIncludedAssemblies.IncludeAssemblyStruct> m_included_assemblies_loaded_config;
        private bool m_warning_msg1;
        private bool m_warning_msg2;

        public DialogArtifactConfig(SpecialProject project)
        {
            InitializeComponent();

            m_project = project;

            this.tabControl1.Selected += new TabControlEventHandler(tabControl1_Selected);
        }

        public DialogArtifactConfig(SpecialSolution solution)
        {
            InitializeComponent();

            m_solution = solution;

            this.tabControl1.TabPages.Remove(this.tabGlobalConfig);
            this.tabControl1.TabPages.Remove(this.tabWSPConfig);

            this.tabControl1.Selected += new TabControlEventHandler(tabControl1_Selected);
        }

        void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
            try
            {
                if (tabControl1.SelectedTab.Name == "tabRemoteServer")
                {
                    string msg = null;
                    if (m_project != null)
                    {
                        if (!settingsPageRemote.RemoteServerUse && m_project.IsRemoteConfigFromSolution && !m_warning_msg1)
                        {
                            msg = "Remote config is activated in the solution configuration. Any changes made here will override the solution settings.";
                        }
                    }

                    if (msg == null)
                    {
                        if (!settingsPageRemote.RemoteServerUse && Common.GetUserRegistryParam(SettingsPageRemote.C_PARAM_REMOTE_SERVER_USE, false) == "True" && !m_warning_msg1)
                        {
                            msg = "Remote config is activated in the global settings in the SPVisualDev options page. Any changes made here will override the global settings. To change those go to the Visual Studio tools menu --> Options --> SPVisualDev.";
                        }
                    }

                    if (msg != null)
                    {
                        MessageBox.Show(msg, "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        m_warning_msg1 = true;
                    }

                }

                else if (tabControl1.SelectedTab.Name == "tabWebApp")
                {
                    this.Cursor = Cursors.WaitCursor;
                    Application.DoEvents();

                    this.lstWebApplications.Items.Clear();
                    this.lstWebApplications.Refresh();

                    bool bShowMsg = false;

                    if (m_project != null)
                    {
                        if (!settingsPageRemote.RemoteServerUse && m_project.IsRemoteConfigFromSolution && !m_warning_msg2)
                        {
                            MessageBox.Show("Remote settings are currently read from the solution configuration.", "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            m_warning_msg2 = true;
                        }

                        if (settingsPageRemote.RemoteServerUse &&
                            (string.IsNullOrEmpty(settingsPageRemote.RemoteServerAddress) ||
                             string.IsNullOrEmpty(settingsPageRemote.RemoteServerPort)))
                        {
                            bShowMsg = true;
                        }
                        else if (Connect.S_Client_Install)
                        {
                            if (settingsPageRemote.RemoteServerUse &&
                                (string.IsNullOrEmpty(settingsPageRemote.RemoteServerAddress) ||
                                 string.IsNullOrEmpty(settingsPageRemote.RemoteServerPort)))
                            {
                                bShowMsg = true;
                            }

                            if (!settingsPageRemote.RemoteServerUse && Common.GetUserRegistryParam(SettingsPageRemote.C_PARAM_REMOTE_SERVER_USE, true) != "True")
                                bShowMsg = true;
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(settingsPageRemote.RemoteServerAddress) || string.IsNullOrEmpty(settingsPageRemote.RemoteServerPort))
                        {
                            bShowMsg = true;
                        }
                    }

                    if (bShowMsg)
                    {
                        MessageBox.Show("No remote server was specified. Please specify a remote server in the remote tab.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        RefreshWebAppView();
                    }
                }
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }


        private void RefreshWebAppView()
        {
            MainServiceWrapper svc = null;
            try
            {
                ConnectionDetailsStruct connectionDetails = new ConnectionDetailsStruct();
                if (this.settingsPageRemote.RemoteServerUse)
                {
                    connectionDetails.Address = this.settingsPageRemote.RemoteServerAddress;
                    connectionDetails.Port = int.Parse(this.settingsPageRemote.RemoteServerPort);

                    if (this.settingsPageRemote.RemoteServerUseDifferentCred)
                    {
                        connectionDetails.UserName = this.settingsPageRemote.RemoteServerUserName;
                        connectionDetails.Password = this.settingsPageRemote.RemoteServerPassword;
                    }

                    this.lblWebApplicaiontsListInfo.Text = "Web applications on server " + ((m_project != null) ? m_project.RemoteConnection.Address : m_solution.RemoteConnection.Address);
                }
                else if (Common.GetUserRegistryParam(SettingsPageRemote.C_PARAM_REMOTE_SERVER_USE, true) == "True")
                {
                    connectionDetails.Address = Common.GetUserRegistryParam(SettingsPageRemote.C_PARAM_REMOTE_SERVER_ADDRESS, true);
                    connectionDetails.Port = int.Parse(Common.GetUserRegistryParam(SettingsPageRemote.C_PARAM_REMOTE_SERVER_PORT, true));

                    if (Common.GetUserRegistryParam(SettingsPageRemote.C_PARAM_REMOTE_USE_DIFFERENT_CRED, true) == "True")
                    {
                        try
                        {
                            connectionDetails.UserName = Common.DecryptUsingKeyContainer(Common.GetUserRegistryParam(SettingsPageRemote.C_PARAM_REMOTE_SERVER_USERNAME, false));
                            connectionDetails.Password = Common.DecryptUsingKeyContainer(Common.GetUserRegistryParam(SettingsPageRemote.C_PARAM_REMOTE_SERVER_PASSWORD, false));
                        }
                        catch
                        {
                            connectionDetails.UserName = "";
                            connectionDetails.Password = "";
                        }
                    }

                    this.lblWebApplicaiontsListInfo.Text = "Web applications on server " + ((m_project != null) ? m_project.RemoteConnection.Address : m_solution.RemoteConnection.Address) + ". Using global settings found in Visual Studio menu, tools --> options --> SPVisualDev";

                }
                else
                {
                    connectionDetails.Address = "";
                    connectionDetails.Port = Common.C_WCF_MAIN_SVC_PORT;

                    if (!Connect.S_Client_Install)
                    {
                        if (!SharePointLibrary.CheckIf32bitOn64())
                        {
                            connectionDetails.UseInProc = true;
                        }
                    }

                    this.lblWebApplicaiontsListInfo.Text = "Web applications on local server";
                }

                svc = new MainServiceWrapper(connectionDetails);
                List<IExplorerObjectContainer> listOfwebApps = svc.ServiceProxy.GetChildren(new ExFarm(), "Web applications");

                string[] targetUrls = new string[] { };
                string targetUrlsStr = "";
                if (m_last_config_values.ContainsKey("TargetURL"))
                    if (!string.IsNullOrEmpty(m_last_config_values["TargetURL"]))
                        targetUrlsStr = m_last_config_values["TargetURL"].ToLower();
    
                if (!string.IsNullOrEmpty(targetUrlsStr))
                {
                    targetUrls = targetUrlsStr.Split(';');
                }

                this.lstWebApplications.Items.Clear();

                foreach (ExWebApplication webapp in listOfwebApps)
                {
                    ListViewItem item = new ListViewItem(new string[] { webapp.Title, webapp.Url });
                    item.Checked = (Array.IndexOf(targetUrls, webapp.Url.ToLower()) != -1);

                    this.lstWebApplications.Items.Add(item);
                }

                this.lstWebApplications.Refresh();
                this.lstWebApplications.Focus();
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex, "Failed to retrieve information from server.", false);
            }
            finally
            {
                if (svc != null)
                    svc.Dispose();
            }

        }

        public EnumBuildType PropGCAssemblyBuildType
        {
            get
            {
                if (rdoGCBuildAppBin.Checked)
                    return EnumBuildType.AppBin;
                else if (rdoGCBuildGAC.Checked)
                    return EnumBuildType.GAC;
                else
                    return EnumBuildType.ProjectDefualt;
            }
            set
            {
                if (value == EnumBuildType.AppBin)
                    rdoGCBuildAppBin.Checked = true;
                else if (value == EnumBuildType.GAC)
                    rdoGCBuildGAC.Checked = true;
                else
                    rdoGCBuildProjectDefault.Checked = true;
            }
        }

        public string PropGCProductVersion
        {
            get { return lblGCProductVersion.Text; }
            set { lblGCProductVersion.Text = value; }
        }

        public string AssemblyFullName
        {
            get { return txtAssemblyFullName.Text; }
            set { txtAssemblyFullName.Text = value; }
        }

        private bool m_HasAssemblyOriginatorKeyFile;
        public bool HasAssemblyOriginatorKeyFile
        {
            get { return m_HasAssemblyOriginatorKeyFile; }
            set { m_HasAssemblyOriginatorKeyFile = value; }
        }

        private List<DialogIncludedAssemblies.IncludeAssemblyStruct> m_IncludedAssemblies;
        public List<DialogIncludedAssemblies.IncludeAssemblyStruct> PropWSPIncludedAssemblies
        {
            get { return m_IncludedAssemblies; }
            set { m_IncludedAssemblies = value; }
        }

        public enum EnumBuildType
        {
            ProjectDefualt,
            GAC,
            AppBin
        }

        private void DialogArtifactConfig_Load(object sender, EventArgs e)
        {
            try
            {
                ReadConfig();
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);

                this.Close();
            }
        }

        private void rdoGCBuildGAC_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (rdoGCBuildGAC.Checked && this.Modal && !HasAssemblyOriginatorKeyFile)
                    MessageBox.Show("This option requires an public key token to be assigned to this assembly build before it can be registered correctly in the GAC. Please assign a key directly after finishing the artifact configuration.", "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        private void btnWSPNewSolutionId_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Do you want to generate a new WSP solution id?", "Prompt", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                    return;

                this.txtWSPSolutionId.Text = Guid.NewGuid().ToString("D").ToLower();
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        private void ReadConfig()
        {
            m_last_config_values = new Dictionary<string, string>();

            if (m_project != null)
            {
                this.txtGCASPXPagesNSsuffix.Text = Common.GetProjectGlobalConfigKey(m_project.Project, "ASPXPagesNSsuffix");
                m_last_config_values.Add("ASPXPagesNSsuffix", this.txtGCASPXPagesNSsuffix.Text);

                this.txtGCMasterPagesNSsuffix.Text = Common.GetProjectGlobalConfigKey(m_project.Project, "MasterPagesNSsuffix");
                m_last_config_values.Add("MasterPagesNSsuffix", this.txtGCMasterPagesNSsuffix.Text);

                this.txtGCWebCustomControlsNSsuffix.Text = Common.GetProjectGlobalConfigKey(m_project.Project, "WebCustomConstrolNSsuffix");
                m_last_config_values.Add("WebCustomConstrolNSsuffix", this.txtGCWebCustomControlsNSsuffix.Text);

                this.txtGCWebPartsNSSuffix.Text = Common.GetProjectGlobalConfigKey(m_project.Project, "WebPartsNSsuffix");
                m_last_config_values.Add("WebPartsNSsuffix", this.txtGCWebPartsNSSuffix.Text);

                this.txtWSPSolutionId.Text = Common.GetProjectGlobalConfigKey(m_project.Project, "WSPSolutionId");
                m_last_config_values.Add("WSPSolutionId", this.txtWSPSolutionId.Text);

                this.txtWSPAdditionalSwitches.Text = Common.GetProjectGlobalConfigKey(m_project.Project, "WSPAdditionalSwitches");
                m_last_config_values.Add("WSPAdditionalSwitches", this.txtWSPAdditionalSwitches.Text);

                this.PropGCProductVersion = "Version " + ((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)[0]).Version + " ";

                try
                {
                    string asm_name = Common.GetTargetBuildAssemblyName(m_project.Project, true);
                    this.AssemblyFullName = asm_name;
                    this.HasAssemblyOriginatorKeyFile = (!string.IsNullOrEmpty((string)m_project.Project.Properties.Item("AssemblyOriginatorKeyFile").Value));
                }
                catch (Exception ex)
                {
                    this.AssemblyFullName = "Error reading assemby information. " + ex.Message;
                }

                this.PropWSPIncludedAssemblies = m_project.GetIncludedAssemblies();
                m_included_assemblies_loaded_config = new List<DialogIncludedAssemblies.IncludeAssemblyStruct>(this.PropWSPIncludedAssemblies);


                string build_type = Common.GetProjectGlobalConfigKey(m_project.Project, "AssemblyBuildType");
                m_last_config_values.Add("AssemblyBuildType", build_type);
                if (build_type == "GAC")
                    this.PropGCAssemblyBuildType = EnumBuildType.GAC;
                else if (build_type == "AppBin")
                    this.PropGCAssemblyBuildType = EnumBuildType.AppBin;
                else
                    this.PropGCAssemblyBuildType = EnumBuildType.ProjectDefualt;



                this.txtWSPBuildOutputPath.Text = m_project.GetUserSettingsValue("WSPBuildOutputPath");
                m_last_config_values.Add("WSPBuildOutputPath", this.txtWSPBuildOutputPath.Text);

            }

            if (m_solution != null)
            {
                m_last_config_values.Add("TargetURL", m_solution.GetUserSettingsValue("TargetURL"));
            }
            else
            {
                m_last_config_values.Add("TargetURL", m_project.GetUserSettingsValue("TargetURL"));
            }

            //Remote settings
            string s = (m_project != null) ? m_project.GetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_USE) : m_solution.GetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_USE);
            bool remote_server_use = string.IsNullOrEmpty(s) ? false : bool.Parse(s);
            m_last_config_values.Add(SettingsPageRemote.C_PARAM_REMOTE_SERVER_USE, s);


            string remote_server_address = (m_project != null) ? m_project.GetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_ADDRESS) : m_solution.GetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_ADDRESS);
            string remote_server_port = (m_project != null) ? m_project.GetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_PORT) : m_solution.GetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_PORT);
            m_last_config_values.Add(SettingsPageRemote.C_PARAM_REMOTE_SERVER_ADDRESS, remote_server_address);
            m_last_config_values.Add(SettingsPageRemote.C_PARAM_REMOTE_SERVER_PORT, remote_server_port);

            s = (m_project != null) ? m_project.GetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_USE_DIFFERENT_CRED) : m_solution.GetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_USE_DIFFERENT_CRED);
            bool remote_server_use_different_cred = string.IsNullOrEmpty(s) ? false : bool.Parse(s);
            m_last_config_values.Add(SettingsPageRemote.C_PARAM_REMOTE_USE_DIFFERENT_CRED, s);

            this.settingsPageRemote.RemoteServerUse = remote_server_use;
            this.settingsPageRemote.RemoteServerAddress = remote_server_address;
            this.settingsPageRemote.RemoteServerPort = remote_server_port;
            this.settingsPageRemote.RemoteServerUseDifferentCred = remote_server_use_different_cred;

            string remote_server_user = null;
            string remote_server_password = null;

            if (this.settingsPageRemote.RemoteServerUseDifferentCred)
            {
                try
                {
                    if (m_project != null)
                    {
                        remote_server_user = Common.DecryptUsingKeyContainer(m_project.GetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_USERNAME));
                        remote_server_password = Common.DecryptUsingKeyContainer(m_project.GetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_PASSWORD));
                    }
                    else
                    {
                        remote_server_user = Common.DecryptUsingKeyContainer(m_solution.GetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_USERNAME));
                        remote_server_password = Common.DecryptUsingKeyContainer(m_solution.GetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_PASSWORD));
                    }
                }
                catch (System.Security.Cryptography.CryptographicException)
                {
                    remote_server_user = null;
                }

                if (remote_server_user != null && remote_server_use_different_cred && remote_server_user.StartsWith("SPVD;"))
                {
                    this.settingsPageRemote.RemoteServerUserName = remote_server_user.Substring(5);
                    this.settingsPageRemote.RemoteServerPassword = remote_server_password;
                }
                else
                {
                    this.settingsPageRemote.RemoteServerUseDifferentCred = false;
                    this.settingsPageRemote.RemoteServerUserName = "";
                    this.settingsPageRemote.RemoteServerPassword = "";

                    remote_server_user = null;
                    remote_server_password = null;
                    remote_server_use_different_cred = false;
                }
            }

            m_last_config_values.Add(SettingsPageRemote.C_PARAM_REMOTE_SERVER_USERNAME, remote_server_user);
            m_last_config_values.Add(SettingsPageRemote.C_PARAM_REMOTE_SERVER_PASSWORD, remote_server_password);

            if (m_project != null)
            {
                this.settingsPageRemote.SetDTE(m_project.Project.DTE);
            }
            else
            {
                this.settingsPageRemote.SetDTE(m_solution.DTE);
            }
            this.settingsPageRemote.SetFieldVisibleStates();

        }

        private void WriteConfig()
        {
            bool bChanged = false;
            bool bIncludedAsmChanged = false;
            string incl_assemblies_wsp = "";
            string incl_assemblies_build = "";
            
            if (m_project != null)
            {
                bChanged = (m_last_config_values["ASPXPagesNSsuffix"] != this.txtGCASPXPagesNSsuffix.Text);
                bChanged = bChanged || (m_last_config_values["MasterPagesNSsuffix"] != this.txtGCMasterPagesNSsuffix.Text);
                bChanged = bChanged || (m_last_config_values["WebCustomConstrolNSsuffix"] != this.txtGCWebCustomControlsNSsuffix.Text);
                bChanged = bChanged || (m_last_config_values["WebPartsNSsuffix"] != this.txtGCWebPartsNSSuffix.Text);
                bChanged = bChanged || (m_last_config_values["AssemblyBuildType"] != this.PropGCAssemblyBuildType.ToString());
                bChanged = bChanged || (m_last_config_values["WSPSolutionId"] != this.txtWSPSolutionId.Text);
                bChanged = bChanged || (m_last_config_values["WSPAdditionalSwitches"] != this.txtWSPAdditionalSwitches.Text);

                if (this.PropWSPIncludedAssemblies != null)
                {
                    foreach (DialogIncludedAssemblies.IncludeAssemblyStruct asm in this.PropWSPIncludedAssemblies)
                    {
                        if (asm.IncludeInWSP)
                        {
                            if (incl_assemblies_wsp != "")
                                incl_assemblies_wsp += ";";

                            incl_assemblies_wsp += asm.Name.Replace(";","_");
                        }

                        if (asm.IncludeWhenBuilding)
                        {
                            if (incl_assemblies_build != "")
                                incl_assemblies_build += ";";

                            incl_assemblies_build += asm.Name.Replace(";","_");
                        }
                    }

                    for (int n = 0; n < m_included_assemblies_loaded_config.Count; n++)
                    {
                        DialogIncludedAssemblies.IncludeAssemblyStruct incl = m_included_assemblies_loaded_config[n];

                        if (incl.Name != this.PropWSPIncludedAssemblies[n].Name ||
                            incl.IncludeInWSP != this.PropWSPIncludedAssemblies[n].IncludeInWSP ||
                            incl.IncludeWhenBuilding != this.PropWSPIncludedAssemblies[n].IncludeWhenBuilding)
                        {
                            bChanged = true;
                            bIncludedAsmChanged = true;
                        }
                    }
                }

                if (bChanged)
                {
                    Common.SetProjectGlobalConfigKey(m_project.Project, "ASPXPagesNSsuffix", this.txtGCASPXPagesNSsuffix.Text, true);
                    Common.SetProjectGlobalConfigKey(m_project.Project, "MasterPagesNSsuffix", this.txtGCMasterPagesNSsuffix.Text, true);
                    Common.SetProjectGlobalConfigKey(m_project.Project, "WebCustomConstrolNSsuffix", this.txtGCWebCustomControlsNSsuffix.Text, true);
                    Common.SetProjectGlobalConfigKey(m_project.Project, "WebPartsNSSuffix", this.txtGCWebPartsNSSuffix.Text, true);
                    Common.SetProjectGlobalConfigKey(m_project.Project, "AssemblyBuildType", this.PropGCAssemblyBuildType.ToString(), true);
                    Common.SetProjectGlobalConfigKey(m_project.Project, "WSPSolutionId", this.txtWSPSolutionId.Text, true);
                    Common.SetProjectGlobalConfigKey(m_project.Project, "WSPAdditionalSwitches", this.txtWSPAdditionalSwitches.Text, true);
                    Common.SetProjectGlobalConfigKey(m_project.Project, "IncludedAssemblies", incl_assemblies_wsp, true);

                    bool isProjectUnderSCC = m_project.Project.DTE.SourceControl.IsItemUnderSCC(m_project.Project.FullName);
                    if (isProjectUnderSCC)
                    {
                        bool isProjectCheckedOut = m_project.Project.DTE.SourceControl.IsItemCheckedOut(m_project.Project.FullName);
                        if (!isProjectCheckedOut)
                            m_project.Project.DTE.SourceControl.CheckOutItem(m_project.Project.FullName);
                    }

                    m_project.Project.Save(m_project.Project.FullName);
                }
            }


            //Local user settings.

            string targetWebAppUrls = "";
            foreach (ListViewItem item in this.lstWebApplications.Items)
            {
                if (!item.Checked)
                    continue;

                if (targetWebAppUrls != "")
                    targetWebAppUrls += ";";

                targetWebAppUrls += item.SubItems[1].Text;
            }

            bChanged = bIncludedAsmChanged;

            if (m_project != null)
            {
                bChanged = bChanged || (m_last_config_values["WSPBuildOutputPath"] != this.txtWSPBuildOutputPath.Text);
            }

            bChanged = bChanged || (m_last_config_values["TargetURL"] != targetWebAppUrls);
            bChanged = bChanged || (m_last_config_values[SettingsPageRemote.C_PARAM_REMOTE_SERVER_USE] != this.settingsPageRemote.RemoteServerUse.ToString());
            bChanged = bChanged || (m_last_config_values[SettingsPageRemote.C_PARAM_REMOTE_SERVER_ADDRESS] != this.settingsPageRemote.RemoteServerAddress);
            bChanged = bChanged || (m_last_config_values[SettingsPageRemote.C_PARAM_REMOTE_SERVER_PORT] != this.settingsPageRemote.RemoteServerPort);
            bChanged = bChanged || (m_last_config_values[SettingsPageRemote.C_PARAM_REMOTE_USE_DIFFERENT_CRED] != this.settingsPageRemote.RemoteServerUseDifferentCred.ToString());
            bChanged = bChanged || (m_last_config_values[SettingsPageRemote.C_PARAM_REMOTE_SERVER_USERNAME] != this.settingsPageRemote.RemoteServerUserName);
            bChanged = bChanged || (m_last_config_values[SettingsPageRemote.C_PARAM_REMOTE_SERVER_PASSWORD] != this.settingsPageRemote.RemoteServerPassword);


            if (bChanged)
            {
                if (m_project != null)
                {
                    m_project.SetUserSettingsValue("TargetURL", targetWebAppUrls, false);
                    m_project.SetUserSettingsValue("IncludedReferencedAssemblies", incl_assemblies_build, false);
                    m_project.SetUserSettingsValue("WSPBuildOutputPath", this.txtWSPBuildOutputPath.Text, false);
                }
                else
                {
                    m_solution.SetUserSettingsValue("TargetURL", targetWebAppUrls, false);
                }


                if (this.settingsPageRemote.RemoteServerUse)
                {
                    if (string.IsNullOrEmpty(this.settingsPageRemote.RemoteServerAddress))
                    {
                        throw new Exception("Invalid remote server adress");
                    }

                    if (string.IsNullOrEmpty(this.settingsPageRemote.RemoteServerPort))
                    {
                        throw new Exception("Invalid remote server port");
                    }
                }

                if (m_project != null)
                {
                    m_project.SetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_USE, this.settingsPageRemote.RemoteServerUse.ToString(), false);
                    m_project.SetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_ADDRESS, this.settingsPageRemote.RemoteServerAddress, false);
                    m_project.SetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_PORT, this.settingsPageRemote.RemoteServerPort, false);
                    m_project.SetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_USE_DIFFERENT_CRED, this.settingsPageRemote.RemoteServerUseDifferentCred.ToString(), false);

                    if (this.settingsPageRemote.RemoteServerUseDifferentCred)
                    {
                        m_project.SetUserSettingsValue(
                            SettingsPageRemote.C_PARAM_REMOTE_SERVER_USERNAME,
                            Common.EncryptUsingKeyContainer("SPVD;" + this.settingsPageRemote.RemoteServerUserName),
                            false);

                        m_project.SetUserSettingsValue(
                            SettingsPageRemote.C_PARAM_REMOTE_SERVER_PASSWORD,
                            Common.EncryptUsingKeyContainer(this.settingsPageRemote.RemoteServerPassword),
                            false);
                    }

                    m_project.SaveSettings();
                    m_project.ReloadServiceProxy();
                }
                else
                {
                    m_solution.SetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_USE, this.settingsPageRemote.RemoteServerUse.ToString(), false);
                    m_solution.SetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_ADDRESS, this.settingsPageRemote.RemoteServerAddress, false);
                    m_solution.SetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_SERVER_PORT, this.settingsPageRemote.RemoteServerPort, false);
                    m_solution.SetUserSettingsValue(SettingsPageRemote.C_PARAM_REMOTE_USE_DIFFERENT_CRED, this.settingsPageRemote.RemoteServerUseDifferentCred.ToString(), false);

                    if (this.settingsPageRemote.RemoteServerUseDifferentCred)
                    {
                        m_solution.SetUserSettingsValue(
                            SettingsPageRemote.C_PARAM_REMOTE_SERVER_USERNAME,
                            Common.EncryptUsingKeyContainer("SPVD;" + this.settingsPageRemote.RemoteServerUserName),
                            false);

                        m_solution.SetUserSettingsValue(
                            SettingsPageRemote.C_PARAM_REMOTE_SERVER_PASSWORD,
                            Common.EncryptUsingKeyContainer(this.settingsPageRemote.RemoteServerPassword),
                            false);
                    }

                    m_solution.SaveSettings();
                    m_solution.ReloadServiceProxy();
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                WriteConfig();

                this.DialogResult = DialogResult.OK;
                this.Hide();
            }
            catch(Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        private void btnEditIncludedAssemblies_Click(object sender, EventArgs e)
        {
            try
            {
                using (DialogIncludedAssemblies dlg = new DialogIncludedAssemblies())
                {
                    dlg.Assemblies = m_IncludedAssemblies;
                    DialogResult result = dlg.ShowDialog(this);

                    if (result == DialogResult.OK)
                    {
                        m_IncludedAssemblies = dlg.Assemblies;
                    }
                }
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        private void btnWSPOutputPath_Click(object sender, EventArgs e)
        {
            try
            {
                this.folderBrowserDialog1.ShowNewFolderButton = true;
                this.folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Desktop;

                DialogResult result = this.folderBrowserDialog1.ShowDialog(this);
                if (result != DialogResult.OK)
                    return;

                this.txtWSPBuildOutputPath.Text = this.folderBrowserDialog1.SelectedPath;
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        
    }
}